import { Injectable } from '@nestjs/common';
import { CreateRoleDto,UpdateRoleDto} from './dto';
import { Repository,In, Not } from 'typeorm';
import { InjectRepository} from '@nestjs/typeorm';
import { Role } from './entities/role.entity';
import { SysRoleWithMenuEntity } from './entities/role.menu.entity';
import {ResultData} from '../../../common/utils/result';

import { v4 as uuidv4 } from 'uuid';
@Injectable()
export class RoleService {

  constructor(
    @InjectRepository(Role)
    private rolesRepository: Repository<Role>,
    @InjectRepository(SysRoleWithMenuEntity)
    private readonly sysRoleWithMenuEntityRep: Repository<SysRoleWithMenuEntity>,
  ) {}

  async add(role: CreateRoleDto) {
    role.create_time = new Date().toLocaleString();
    role.roleid = uuidv4();
    const res = await this.rolesRepository.insert(role)
    return ResultData.ok(res);
  }

  async findPage(query,req) {
    const entity = this.rolesRepository.createQueryBuilder('sys_role');
    if (query.pageSize && query.pageNum) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }
    const [list, total] = await entity.getManyAndCount();
    const data =  {
      total:total,
      data:list,
    }
    return ResultData.ok(data);
  }

  async find(){
    const res = await this.rolesRepository.find();
    return ResultData.ok(res);
  }

  async findOne(roleid: string) {
    const data =  await this.rolesRepository.findOne({
        where:{
          roleid:roleid
        }
    })
    return ResultData.ok(data);
  }

  async update(role: UpdateRoleDto) {
    role.update_time = new Date().toLocaleString();
    const res = await this.rolesRepository.update({ roleid: role.roleid }, role) 
    return ResultData.ok(res);
  }

  async remove(ids:string[]) {
    const res = await this.rolesRepository.update(
      { roleid: In(ids)},
      {
        status: '2',//禁用
      },
    )
    return ResultData.ok(res);
  }

  async addRoleMenu(roleid:string,menuids:string[]) {
    console.log(menuids,'menuids')
    await this.sysRoleWithMenuEntityRep.delete({
      roleid: roleid,
    });
    menuids.map(async item=>{
        await this.sysRoleWithMenuEntityRep.insert({
          roleid: roleid,
          menuid: item
        })
    })
    return ResultData.ok();
    //const res = await this.rolesRepository.update({ roleid }, { menus: In(menuIds) });
    //return ResultData.ok(res);
  }
}
